<?
/**
 * VoiceOne Settings/Offices/edit
 *
 * Frontend to provide access to the offices system in voiceone.
 * @package voiceone
 * @subpackage  settings_offices
 */

  include ("../../../../admin/config/cfg.php");
  global $cwlang, $cwLanguage;
 	require_once("$absBasePath/lib/xajax/xajax.inc.php");
 	sajax_init();

  //================ XAJAX ================
	function showCid($id){
    global $asterisk,$cwlang;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
		// Build response
    if($id!=""){
      $ret=$asterisk->getOffice($id);
      if ($err=$asterisk->getError()) die("Error: $err");
      $cid_force=$ret[0]["force_cid"];
      $cid_clir=$ret[0]["clir"];
      $cid_number=$ret[0]["cid_number"];
      $cid_name=$ret[0]["cid_name"];
      $cid_appexten=$ret[0]["cid_appexten"];
    }
    ob_start();
    ?>
        <dl>
          <dt class="required"><label for="cid[cid_name]"><?=T_("CID Name")?>:</label></dt>
          <dd><input type="text" size="25" maxlength="20" id="cid[cid_name]" name="cid[cid_name]" value="<?=$cid_name?>" /> <?=T_("default caller id name")?></dd>
          <dt class="required"><label for="cid[cid_number]"><?=T_("CID Number")?>:</label></dt>
          <dd><input type="text" size="25" maxlength="100" id="cid[cid_number]" name="cid[cid_number]" value="<?=$cid_number?>" /> <?=T_("default caller id number")?></dd>
          <dt class="required"><label for="cid[cid_appexten]"><?=T_("Append Exten")?>:</label></dt>
          <dd><input type="checkbox" id="cid[cid_appexten]" name="cid[cid_appexten]" value="1" <?if ($cid_appexten==1) echo "checked=\"checked\""; ?> /> <?=T_("append user's extension to CID Number value")?></dd>
          <dt class="required"><label for="cid[force_cid]"><?=T_("Force Default")?>:</label></dt>
          <dd><input type="checkbox" id="cid[force_cid]" name="cid[force_cid]" value="1" <?if ($cid_force==1) echo "checked=\"checked\""; ?> /> <?=T_("overwrite user's caller id setting with default line values")?></dd>
        </dl>
    <?
    $html=ob_get_contents();
    ob_end_clean();
    // Return the xajaxResponse object
		$objResponse->addAssign("callerid","innerHTML",$html);
    return $objResponse->getXML();
  }
  function hideCid(){
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
		// Build response
    $html="";
    // Return the xajaxResponse object
		$objResponse->addAssign("callerid","innerHTML",$html);
    return $objResponse->getXML();
  }
  function setInKey($host){
    global $asterisk,$cwlang;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
		// Remote account
    $key="";
    if($host!=""){
      $url = "http://".$host."/voiceone_webservices/sandbox/mypbx.pub";
      ini_set('default_socket_timeout', "5");
      $fp = @fopen($url,"r");
      $key = @fread($fp,1024);
      @fclose($fp);
    }
    // Return the xajaxResponse object
    if($key=="") $objResponse->addScript(" alert('".sprintf(T_("Unable to connect to host \"%s\""),$host )."'); ");
		else{
      $objResponse->addAssign("off[inkey]","innerHTML",$key);
      $objResponse->addAssign("off[inkey]","value",$key);
    }
    $objResponse->addAssign("inKeyRoll","innerHTML","");
    return $objResponse->getXML();
  }
  function authRSA($id,$host){
    global $asterisk,$cwlang;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
		// Remote account
    if($host=="") $disabled="disabled=\"disabled\"";
    if($id!=""){
      $ret=$asterisk->getOffice($id);
      if(is_array($ret)){
        $v=$ret[0];
        $inkey=$v["inkey"];
      }
    }
    ob_start();
    ?>
      <dl>
        <dt class="required"><label for="off[inkey]"><?=T_("RSA key")?>:</label></dt>
        <dd><textarea rows="5" cols="65" style="font-size:x-small; width: 60%;" id="off[inkey]" name="off[inkey]"><?=$inkey?></textarea>  <span id="rsakeyErr"><span></dd>
        <dt class="required"><label for="button1"></label></dt>
        <dd>
          <table>
            <tr>
              <td><input type="button" id="getKeyButton" value="<?=T_("Get Key")?>" <?=$disabled?> onclick=" setInKeyRoll(); xajax_setInKey(document.getElementById('off[host]').value); "/></td>
              <td><span id="inKeyRoll"></span></td>
            </tr>
          </table>
        </dd>
      </dl>
    <?
    $html_remote=ob_get_contents();
    ob_end_clean();
    // Local Account
    $localPubblicKey=nl2br($asterisk->getPublicKey());
    $localPubblicKey=str_replace("<br />","",$localPubblicKey);
    ob_start();
    ?>
      <dl>
        <dt class="required"><label for="off[outkey]"><?=T_("RSA key")?>:</label></dt>
        <dd><textarea rows="5" cols="65" style="font-size:x-small; width: 60%;" id="off[outkey]" name="off[outkey]" readonly="readonly" ><?=$localPubblicKey?></textarea></dd>
      </dl>
    <?
    $html_local=ob_get_contents();
    ob_end_clean();
    // Return the xajaxResponse object
		$objResponse->addAssign("auth_method_remote","innerHTML",$html_remote);
    $objResponse->addAssign("auth_method_local","innerHTML",$html_local);
    return $objResponse->getXML();
  }
  function authPWD($password){
    global $cwlang;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
		// Build response
    ob_start();
    ?>
      <dl>
        <dt class="required"><label for="off[password]"><?=T_("Password")?>:</label></dt>
        <dd>
          <input type="password" size="25" maxlength="20" id="off[password]" name="off[password]" value="<?=$password?>" onkeyup="document.getElementById('off[localpassword]').value=this.value;document.getElementById('off[localconfirm]').value=this.value;"  onblur="document.getElementById('off[localpassword]').value=this.value;document.getElementById('off[localconfirm]').value=this.value;"/>
          <span id="passwordErr"></span><span class="help"><?=T_("Set the password")?></span>
        </dd>
        <dt class="required"><label for="off[confirm]"><?=T_("Confirm")?>:</label></dt>
        <dd><input type="password" size="25" maxlength="20" id="off[confirm]" name="off[confirm]" value="<?=$password?>" /> <span id="confirmErr"></span><span class="help"><?=T_("Confirm the password")?></span></dd>
      </dl>
    <?
    $html_remote=ob_get_contents();
    ob_end_clean();
    ob_start();
    ?>
      <dl>
        <dt class="required"><label for="off[localpassword]"><?=T_("Password")?>:</label></dt>
        <dd><input type="password" size="25" maxlength="20" id="off[localpassword]" name="off[localpassword]" value="<?=$password?>" readonly="readonly" /> <span id="passwordErr"></span><span class="help"><?=T_("Set the password")?></span></dd>
        <dt class="required"><label for="off[localconfirm]"><?=T_("Confirm")?>:</label></dt>
        <dd><input type="password" size="25" maxlength="20" id="off[localconfirm]" name="off[localconfirm]" value="<?=$password?>" readonly="readonly" /> <span id="confirmErr"></span><span class="help"><?=T_("Confirm the password")?></span></dd>
      </dl>
    <?
    $html_local=ob_get_contents();
    ob_end_clean();
    // Return the xajaxResponse object
		$objResponse->addAssign("auth_method_remote","innerHTML",$html_remote);
    $objResponse->addAssign("auth_method_local","innerHTML",$html_local);
    return $objResponse->getXML();
  }
	function roll(){
    global $relBasePath,$cwlang;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Build response
    $html=" <img src=\"".$relBasePath."public/img/ico-progress.gif"."\" alt=\"loading\" /><span>".T_("loading")."</span>";
    $objResponse->addAssign("loading","innerHTML",$html);
    // Return the xajaxResponse object
    return $objResponse->getXML();
  }
  function processFormData($formData){
    global $asterisk,$cwlang,$relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Extract form's params
    $office=$formData["off"];
    $id=$office["id"];
    $name=$office["name"];
    $label=$office["label"];
    $host=$office["host"];
    $port=$office["port"];
    $aliasArr=$office["alias"];
    $inkey=$office["inkey"];
    $method=$office["method"];
    $username=$office["username"];
    $password=$office["password"];
    $confirm=$office["confirm"];
    $speeddial=$office["speeddial"];
    $oldSpeeddial=$office["oldSpeeddial"];
    $phonenumberArr=$formData["phonenumber"];
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">&nbsp;&nbsp;";
    // Retrieve all accounts
    $officeArr=$asterisk->getOffice(0);
    if(is_array($officeArr)){
    	$offNumberArr=array();
      $offNameArr=array();
      $offLabelArr=array();
      $offHostArr=array();
      foreach($officeArr as $off){
        if($id==$off["id"]){
        	if(is_array($off["numbers"])) $offNumberArr=$off["numbers"];
        	continue;
        }
        $offNameArr[]=$off["name"];
        $offLabelArr[]=$off["label"];
        $offHostArr[]=$off["host"].":".$off["port"];
      }
    }
    // Retrieve Extensions
    $extensionArr=$asterisk->getExtension(0);
    if(is_array($extensionArr)){
      foreach($extensionArr as $ext){
        if(($id==$ext["entity_id"])||($oldSpeeddial."*"==$ext["extension"])) continue;
        $extNumberArr[]=$ext["extension"];
      }
    }
    // Check Label ((not null)&&(unique))
    $labelErr=false;
    if($label=="") {
      //name cannot be null
      $errOut[]=T_("Name cannot be null");
      $objResponse->addAssign("labelErr","innerHTML",$imgErr);
      $nameErr=true;
    }else if((is_array($offLabelArr))&&(in_array($label,$offLabelArr))){
      //name must be unique
      $errOut[]=T_("Name already exists. Please change it");
      $objResponse->addAssign("labelErr","innerHTML",$imgErr);
      $labelErr=true;
    }
    if($labelErr===false) $objResponse->addAssign("labelErr","innerHTML","");
    // Check Host:Port ((not null)&&(unique))
    $hostErr=false;
    $portErr=false;
    if($host=="") {
      //host cannot be null
      $errOut[]= T_("Host cannot be null");
      $objResponse->addAssign("hostErr","innerHTML",$imgErr);
      $hostErr=true;
    }
    else if((is_array($offHostArr))&&(in_array($host.":".$port,$offHostArr))){
      //host must be unique
      $errOut[]= T_("Host already exists. Please change it");
      $objResponse->addAssign("hostErr","innerHTML",$imgErr);
      $objResponse->addAssign("portErr","innerHTML",$imgErr);
      $hostErr=true;
      $portErr=true;
    }
    if($hostErr===false) {
      $objResponse->addAssign("hostErr","innerHTML","");
      $objResponse->addAssign("portErr","innerHTML","");
    }
    // Check Port ((null)or(numeric))
    if(($port!="")&&($portErr!==true)){
      //port must be numeric
      for($i=0; $i<strlen($port); $i++){
        $ch=ord($port[$i]);
        if(!((($ch>47)&&($ch<58)))){
          $errOut[]=T_("Port allows only numeric characters. Please change it");
          $objResponse->addAssign("portErr","innerHTML",$imgErr);
          $portErr=true;
          break;
        }
      }
    }
    if($portErr===false) $objResponse->addAssign("portErr","innerHTML","");
    // Check Alias ((null)or(unique in extension table))
    $aliasErr=false;
    if(is_array($aliasArr)){
      //Alias must be unique in extension table
      foreach($aliasArr as $number){
        if((is_array($extNumberArr))&&(in_array($number,$extNumberArr))){
          $errOut[]=T_("Some aliases are already in use by another entity");
          $objResponse->addAssign("aliasErr","innerHTML",$imgErr);
          $aliasErr=true;
          break;
        }
      }
    }
    if($aliasErr===false) $objResponse->addAssign("aliasErr","innerHTML","");
    // Check Username_remote ((not null)&&(only alphanumeric char))
    $usernameErr=false;
    if($username==""){
      //remote username cannot be null
      $errOut[]=T_("Remote username cannot be null");
      $objResponse->addAssign("usernameErr","innerHTML",$imgErr);
      $usernameErr=true;
    }else{
      //remote username must have no spaces
      for($i=0; $i<strlen($username); $i++){
        $ch=ord($username[$i]);
        if($ch==32){
          $errOut[]=T_("Remote username doesn't allow spaces. Please change it");
          $objResponse->addAssign("usernameErr","innerHTML",$imgErr);
          $usernameErr=true;
          break;
        }
        //remote usernname must be alphanumeric
        if(!((($ch>96)&&($ch<123))||(($ch>64)&&($ch<91))||(($ch>47)&&($ch<58)))){
          $errOut[]=sprintf(T_("Remote username doesn't allow character \"%s\" Please change it."),$username[$i] );;
          $objResponse->addAssign("usernameErr","innerHTML",$imgErr);
          $usernameErr=true;
          break;
        }
      }
    }
    if($usernameErr===false) $objResponse->addAssign("usernameErr","innerHTML","");
    // Check Account Password ((no null)&&(==confirm)&&(alphanumeric)&&(no spaces))
    $passwordErr=false;
    if($method==0){ //auth with password
      if($password==""){
        //account password cannot be null
        $errOut[]=T_("Password cannot be null");
        $objResponse->addAssign("passwordErr","innerHTML",$imgErr);
        $passwordErr=true;
      }else if($password!=$confirm){
        //account password must be equal to confirm
        $errOut[]=T_("Password and confirmation password do not match");
        $objResponse->addAssign("passwordErr","innerHTML",$imgErr);
        $objResponse->addAssign("confirmErr","innerHTML",$imgErr);
        $passwordErr=true;
      }else{
        //account password must have no spaces
        for($i=0; $i<strlen($password); $i++){
          $ch=ord($password[$i]);
          if($ch==32){
            $errOut[]=T_("Password doesn't allow spaces. Please change it");
            $objResponse->addAssign("passwordErr","innerHTML",$imgErr);
            $passwordErr=true;
            break;
          }
        }
      }
    }
    if($passwordErr===false){
      $objResponse->addAssign("passwordErr","innerHTML","");
      $objResponse->addAssign("confirmErr","innerHTML","");
    }
    // Check name ((not null)&&(unique)&&(only alphanumeric char))
    // [name is tagged as local username]
    $nameErr=false;
    if($name=="") {
      //local usernname cannot be null
      $errOut[]= T_("Local username cannot be null");
      $objResponse->addAssign("nameErr","innerHTML",$imgErr);
      $nameErr=true;
    }else if((is_array($offNameArr))&&(in_array($name,$offNameArr))){
      //local usernname must be unique
      $errOut[]= T_("Local username already exists. Please change it");
      $objResponse->addAssign("nameErr","innerHTML",$imgErr);
      $nameErr=true;
    }else{
      for($i=0; $i<strlen($name); $i++){
        $ch=ord($name[$i]);
        //local usernname must have no spaces
        if($ch==32){
          $errOut[]=T_("Local username doesn't allow spaces. Please change it");
          $objResponse->addAssign("nameErr","innerHTML",$imgErr);
          $nameErr=true;
          break;
        }
        //local usernname must be alphanumeric
        if(!((($ch>96)&&($ch<123))||(($ch>64)&&($ch<91))||(($ch>47)&&($ch<58)))){
          $errOut[]=sprintf(T_("Local username doesn't allow character \" %s \" Please change it."),$username_local[$i] );
          $objResponse->addAssign("nameErr","innerHTML",$imgErr);
          $nameErr=true;
          break;
        }
      }
    }
    if($nameErr===false) $objResponse->addAssign("nameErr","innerHTML","");
    // Check RSA Key (no null)
    $rsakeyErr=false;
    if($method==1){ //auth with rsa key
      if($inkey==""){
        //rsa key cannot be null
        $errOut[]=T_("RSA Key cannot be null");
        $objResponse->addAssign("rsakeyErr","innerHTML",$imgErr);
        $rsakeyErr=true;
      }
    }
    if($rsakeyErr===false) $objResponse->addAssign("rsakeyErr","innerHTML","");
    // Check Speeddial(((null)or ((numeric)and(unique)) )
    $speedErr=false;
    if($speeddial!=""){
      //speeddial must be numeric
      for($i=0; $i<strlen($speeddial); $i++){
        $ch=ord($speeddial[$i]);
        if(!((($ch>47)&&($ch<58)))){
          $errOut[]=T_("Speed Dial allows only numeric characters. Please change it");
          $objResponse->addAssign("speedErr","innerHTML",$imgErr);
          $speedErr=true;
          break;
        }
      }
      if($speedErr===false){
        //speeddial must be unique
        if((is_array($extNumberArr))&&(in_array($speeddial."*",$extNumberArr))){
          $errOut[]=T_("Speed Dial already in use. Please change it");
          $objResponse->addAssign("speedErr","innerHTML",$imgErr);
          $speedErr=true;
        }
      }
    }
    if($speedErr===false) $objResponse->addAssign("speedErr","innerHTML","");
    // Check Phonenumbers (there are extension's cid settings linked to others numbers
    $extensionList=""; 
    if((trim($id)!="")&&($id!=0)&&(is_array($offNumberArr))&&(count($offNumberArr)>0)){
    	//create array of deleted numbers
    	if(is_array($phonenumberArr)) $diffArr=array_diff($offNumberArr,$phonenumberArr);
			else $diffArr=$offNumberArr;
    	//get cid settings for this trunk
      $ret=$asterisk->getCidFromTrunk($id);
      if(is_array($ret)){
      	foreach($ret as $c){
        	if(in_array($c["cid_number"],$diffArr,true)===true){
          	$client=$asterisk->getClient($c["extension"],0);
            if((is_array($client))&&(is_array($client[0]))){
            	$extensionList.=$client[0]["extension"].", ";
            }
          }
        }
      }
    }
    $pruneScript="";
    if(trim($extensionList)!=""){
    	$extensionList=substr($extensionList,0,-2);
      $pruneScript=sprintf(T_("Some Extensions (%s) use deleted numbers in Cid\\nIf you continue these settings will be deleted.\\nContinue?"),$extensionList);
    }
    // Process Form
    if(isset($errOut)){
      $error="<div class=\"AlertBad\"><ul>";
      foreach($errOut as $err) $error.="<li>".$err."</li>";
      $error.="</ul></div>";
      $objResponse->addAssign("alert","innerHTML",$error);
      $objResponse->addAssign("loading","innerHTML","");
    }else{
      $objResponse->addAssign("loading","innerHTML","");
      if(trim($pruneScript)!="") $objResponse->addScript(" if(confirm('".$pruneScript."')) document.getElementById('mainform').submit(); ");
      else $objResponse->addScript(" document.getElementById('mainform').submit(); ");
    }
    // Return the xajaxResponse object
    return $objResponse->getXML();
  }
  $xajax = new xajax();
	$xajax->registerFunction("showCid");
  $xajax->registerFunction("hideCid");
  $xajax->registerFunction("setInKey");
  $xajax->registerFunction("authRSA");
  $xajax->registerFunction("authPWD");
  $xajax->registerFunction("roll");
  $xajax->registerFunction("processFormData");
  $xajax->processRequests();

  //================= POST  ==================
  if (count($_POST)>0) {
    $data=$_POST["off"];
    if(is_array($data["alias"])){
      for($i=0;$i<count($data["alias"]);$i++) $data["alias"][$i]=trim($data["alias"][$i]);
    }
    $entry=Array(
            "id"        => $data["id"],
            "name"      => $data["name"],
            "label"     => $data["label"],
            "speeddial" => $data["speeddial"],
            "username"  => $data["username"],
            "password"  => $data["password"],
            "inkey"     => $data["inkey"],
            "host"      => $data["host"],
            "port"      => $data["port"],
            "register"  => $data["register"],
            "alias"     => $data["alias"],
            "did"       => $_POST["did"],
            "groups"    => $_POST["group"]
        );
    //add options to the entry
    foreach ($_POST as $k=>$v) {
      if (substr($k,0,7)=="status_") {
        $k=substr($k,7);
        if ($v=="1") {
          $o["key"]=$k;
          $o["value"]=$_POST["option_".$k];
          $options[]=$o;
        }
      }
    }
    $entry["options"]=$options;
    //add cid setting
    $cid=$_POST["cid"];
    if($cid["passthrough"]==1) $entry["enable_cid"]=0;
    else $entry["enable_cid"]=1;
    $entry["force_cid"]=$cid["force_cid"];
    $entry["clir"]=$cid["clir"];
    $entry["cid_number"]=$cid["cid_number"];
    $entry["cid_name"]=$cid["cid_name"];
    $entry["cid_appexten"]=$cid["cid_appexten"];
    //add the phonenumbers
    if (is_array($_POST["phonenumber"]))
    foreach($_POST["phonenumber"] as $pn) $entry["numbers"][]=trim($pn);
    //put office
    $ret=$asterisk->putOffice($entry);
    if ($err=$asterisk->getError()) $alert="<div class=\"AlertBad\">ERROR: $err</div>";
    if ($ret>0) {
      $alert.="<div class=\"AlertGood\">".T_("Provider has been successfully edited")."</div>";
      $_GET["id"]=$ret;
    } else $alert.="<div class=\"AlertBad\">".T_("Provider has NOT been edited")."</div>";
    goToMainPage($alert);
  }

  //================ PAGE LOGIC ================
  //get the client informations
  if (isset($_GET["id"]) and $_GET["id"]!="") {
    $id=$_GET["id"];
    $ret=$asterisk->getOffice($id);
    if ($err=$asterisk->getError()) die("Error: $err");
    $v=$ret[0];
    $id=$v["id"];
    $name=$v["name"];
    $label=$v["label"];
    $speeddial=$v["speeddial"];
    $rule=$v["rule"];
    $username=$v["username"];
    $password=$v["password"];
    $inkey=$v["inkey"];
    $host=$v["host"];
    $port=$v["port"];
    $register=$v["register"];
    $did=$v["did"];
    $optionsArr=$v["options"];
    $groups=$v["groups"];
    $cid=Array(
        "clir"          => $v["clir"],
        "cid_number"    => $v["cid_number"],
        "cid_name"      => $v["cid_name"],
        "cid_appexten"  => $v["cid_appexten"],
        "force_cid"     => $v["force_cid"]
      );
    if($v["enable_cid"]==1) $passthrough=0; else $passthrough=1;
    //create the alias list
    if (is_array($v["alias"])) {
      foreach($v["alias"] as $n) $alias.="<option value='$n'>$n</option>";
    }
    //create the phone number list
    if (is_array($v["numbers"])) {
      foreach($v["numbers"] as $n) $numbers.="<option value='$n'>$n</option>";
    }
    $title=sprintf(T_("Edit Office \"%s\""),$name );
  }
  else $title=T_("New Office");
  //Initialize account sections
  $remoteAuthSection="<dl>";
  $localAuthSection="<dl>";
  if($inkey!=""){
    $checkPWD="";
    $checkRSA="checked=\"checked\"";
    if($host=="") $disabled="disabled=\"disabled\""; else $disabled="";
    $remoteAuthSection.="<dt class=\"required\"><label for=\"off[inkey]\">".T_("RSA key").":</label></dt>\n";
    $remoteAuthSection.="<dd><textarea rows=\"5\" cols=\"65\" style=\"font-size:x-small; width: 60%;\" id=\"off[inkey]\" name=\"off[inkey]\">".$inkey."</textarea> <span id=\"rsakeyErr\"><span></dd>\n";
    $remoteAuthSection.="<dt class=\"required\"><label for=\"button1\"></label></dt>";
    $remoteAuthSection.="<dd><table><tr><td><input type=\"button\" id=\"getKeyButton\" value=\"".T_("Get Key")."\" ".$disabled." onclick=\" setInKeyRoll(); xajax_setInKey(document.getElementById('off[host]').value); \"/></td><td><span id=\"inKeyRoll\"></span></td></tr></table></dd>";
    $localPubblicKey=nl2br($asterisk->getPublicKey());
    $localPubblicKey=str_replace("<br />","",$localPubblicKey);
    $localAuthSection.="<dt class=\"required\"><label for=\"off[outkey]\">".T_("RSA key").":</label></dt>\n";
    $localAuthSection.="<dd><textarea rows=\"5\" cols=\"65\" style=\"font-size:x-small; width: 60%;\" id=\"off[outkey]\" name=\"off[outkey]\" readonly=\"readonly\" >".$localPubblicKey."</textarea></dd>\n";
  }else{
    $checkPWD="checked=\"checked\"";
    $checkRSA="";
    $remoteAuthSection.="<dt class=\"required\"><label for=\"off[password]\">".T_("Password").":</label></dt>\n";
    $remoteAuthSection.="<dd><input type=\"password\" size=\"25\" maxlength=\"20\" id=\"off[password]\" name=\"off[password]\" value=\"".$password."\" onkeyup=\"document.getElementById('off[localpassword]').value=this.value;document.getElementById('off[localconfirm]').value=this.value;\"  onblur=\"document.getElementById('off[localpassword]').value=this.value;document.getElementById('off[localconfirm]').value=this.value;\"/>\n";
    $remoteAuthSection.="<span id=\"passwordErr\"></span><span class=\"help\">".T_("Set the password")."</span></dd>\n";
    $remoteAuthSection.="<dt class=\"required\"><label for=\"off[confirm]\">".T_("Confirm").":</label></dt>\n";
    $remoteAuthSection.="<dd><input type=\"password\" size=\"25\" maxlength=\"20\" id=\"off[confirm]\" name=\"off[confirm]\" value=\"".$password."\" /> <span id=\"confirmErr\"></span><span class=\"help\">".T_("Confirm the password")."</span></dd>";
    $localAuthSection.="<dt class=\"required\"><label for=\"off[localpassword]\">".T_("Password").":</label></dt>\n";
    $localAuthSection.="<dd><input type=\"password\" size=\"25\" maxlength=\"20\" id=\"off[localpassword]\" name=\"off[localpassword]\" value=\"".$password."\" readonly=\"readonly\" /> <span id=\"passwordErr\"></span><span class=\"help\">".T_("Set the password")."</span></dd>\n";
    $localAuthSection.="<dt class=\"required\"><label for=\"off[localconfirm]\">".T_("Confirm").":</label></dt>\n";
    $localAuthSection.="<dd><input type=\"password\" size=\"25\" maxlength=\"20\" id=\"off[localconfirm]\" name=\"off[localconfirm]\" value=\"".$password."\" readonly=\"readonly\" /> <span id=\"confirmErr\"></span><span class=\"help\">".T_("Confirm the password")."</span></dd>";
  }
  $remoteAuthSection.="</dl>";
  $localAuthSection.="</dl>";
  //set default callerid in IAX2 options
  if(!(isset($_GET["id"]) and $_GET["id"]!="")) {
    $optCallerId=array("key" => "159" , "value" => "null");
    $optionsArr[]=$optCallerId;
  }

  //================ MAIN CONTENTS ================
  ob_start();
  $xajax->printJavascript("../../../../admin/lib/xajax/");
  ?>
  <div class="SectionHeader">
    <div id="loading" style="float: right;"></div>
    <h1><?=$title?></h1>
    <h3>
      <a href="../" class="admin" ><?=T_("Back without saving")?></a>
    </h3>
  </div>
  <div id="alert"></div>
  <div id="basic_form">
    <form id="mainform" action="<?=$PHP_SELF?>?id=<?=$_GET["id"]?>" method="post" onSubmit="selectAll(getElementById('off[alias]')); return selectAll(getElementById('phonenumber'));">
      <!-- Office Info -->
      <h2><?=T_("Office Info")?></h2>
      <p class="blockintro"><?=T_("Office general information")?></p>
      <div class="block">
        <dl>
          <dt class="required"><label for="off[label]"><?=T_("Name")?>:</label></dt>
          <dd><input type="text" size="25" maxlength="30" id="off[label]" name="off[label]" value="<?=$label?>" /> <span id="labelErr"></span><span class"help"><?=T_("Enter a name for this office, p.e. FarawayOffice.")?></span></dd>
          <dt class="required"><label for="off[host]"><?=T_("IP address")?>:</label></dt>
          <dd><input type="text" size="25" maxlength="20" id="off[host]" name="off[host]" value="<?=$host?>" onkeyup="if(document.getElementById('getKeyButton')!=null){ if(this.value!='') document.getElementById('getKeyButton').disabled=''; else document.getElementById('getKeyButton').disabled='disabled'; } " /> <span id="hostErr"></span><span class="help"><?=T_("Insert the IP address or the hostname")?></span></dd>
          <dt class="required"><label for="off[port]"><?=T_("Port")?>:</label></dt>
          <dd><input type="text" size="25" maxlength="20" id="off[port]" name="off[port]" value="<?=$port?>" /> <span id="portErr"></span><span class="help"><?=T_("Server port, leave empty for default")?></span></dd>
          <dt class="required"><label for="off[register]"><?=T_("Register")?>:</label></dt>
          <dd><input type="checkbox" name="off[register]" id="off[register]" value="1" <?if ($register=="1") echo "checked=\"checked\"";?>/> <span class="help"><?=T_("If your server has a dynamic IP, you need to send your registration")?></span></dd>
          <table style="margin-left: 59px; width: 80%;">
            <tr>
              <td class="required"><label for="aliasNumber"><?=T_("Alias")?>:</label></td>
              <td class="required"><?=T_("Alias added")?></td>
            </tr>
            <tr>
              <td valign="top">
                <input style="margin-left: 40px;" type="text" size="25" maxlength="100" id="aliasNumber" name="aliasNumber" value="" />
                <input type="button" value="+" onclick="addOption(getElementById('off[alias]'),document.getElementById('aliasNumber').value);document.getElementById('aliasNumber').value='';" title="<?=T_("Add")?>">
                <div style="margin-left: 40px;" class="help"><?=T_("Digit the alias number (i.e. <strong>123456</strong>)<br/>or a range of alias numbers as (<strong>123456-123459</strong>)")?></div>
              </td>
              <td>
                <select name="off[alias][]" size="4" onchange="saved = false" ondblclick="editOptions(this)" multiple style="float: left" id="off[alias]">
                  <?=$alias?>
                </select>
                <input type="button" value="<?=T_("Edit")?>" onclick="editOptions(getElementById('off[alias]'))" title="<?=T_("Edit")?>">
                <input type="button" value="<?=T_("X")?>" onclick="deleteOptions(getElementById('off[alias]'))" title="<?=T_("Delete")?>">
                <span id="aliasErr"></span>
              </td>
            </tr>
          </table>
          <dt class="required"><label for="off[method]"><?=T_("Authentication")?>:</label></dt>
          <dd>
            <table style="width: 20em;" cellpadding="0" cellspacing="0">
              <tr>
                <td style="align: right; width: 1%;"><input type="radio" id="off[method]" name="off[method]" value="0" onclick=" xajax_authPWD('<?=$password?>');" <?=$checkPWD?> /></td>
                <td style="align: left;"><span style="color: #000000;"><?=T_("Plain Text")?></span></td>
                <td style="align: right; width: 1%;"><input type="radio" id="off[method]" name="off[method]" value="1" onclick=" xajax_authRSA('<?=$id?>',document.getElementById('off[host]').value);" <?=$checkRSA?> /></td>
                <td style="align: left;"><span style="color: #000000;"><?=T_("RSA Key")?></span></td>
              </tr>
            </table>
          </dd>
          <dl>
        </dl>
        </dl>
      </div>
      <!-- Remote Account -->
      <h2><?=T_("Remote Account")?></h2>
      <p class="blockintro"><?=T_("Account information to authenticate the local Office to the remote one")?></p>
      <div class="block">
        <dl>
          <dt class="required"><label for="off[username]"><?=T_("Username")?>:</label></dt>
          <dd><input type="text" size="25" maxlength="100" id="off[username]" name="off[username]" value="<?=$username?>" /> <span id="usernameErr"></span></dd>
        </dl>
        <div id="auth_method_remote"><?=$remoteAuthSection?></div>
      </div>
      <!-- Local Account -->
      <h2><?=T_("Local Account")?></h2>
      <p class="blockintro"><?=T_("Account information to authenticate the remote Office to the local one")?></p>
      <div class="block">
        <dl>
          <dt class="required"><label for="off[name]"><?=T_("Username")?>:</label></dt>
          <dd><input type="text" size="25" maxlength="30" id="off[name]" name="off[name]" value="<?=$name?>" /> <span id="nameErr"></dd>
        </dl>
        <div id="auth_method_local"><?=$localAuthSection?></div>
      </div>
      <!-- Setting -->
    	<h2><?=T_("Settings")?></h2>
      <p class="blockintro"><?=T_("Office general settings")?></p>
      <div class="block">
        <dl>
          <dt class="required"><label for="off[speeddial]"><?=T_("Speed Dial")?>:</label></dt>
          <dd>
            <input type="text" size="21" maxlength="50" id="off[speeddial]" name="off[speeddial]" value="<?=$speeddial?>" /><big><span style="color: #000000;"> *</span></big><span id="speedErr">&nbsp;</span><span class"help"><?=T_("Direct selection (e.g. <strong>99</strong> or <strong>3</strong>), leave empty for autoassign")?></span>
            <input type="hidden" maxlength="50" id="off[oldSpeeddial]" name="off[oldSpeeddial]" value="<?=$speeddial?>" />
          </dd>
        </dl>
        <table style="margin-left: 24px;">
          <tr>
            <td class="required"><label for="number"><?=T_("Phone number")?>:</label></td>
            <td class="required"><?=T_("Phone numbers added")?></td>
          </tr>
          <tr>
            <td valign="top">
              <input type="text" size="25" maxlength="100" id="number" name="number" value="" />
              <input type="button" value="+" onclick="addOption(getElementById('phonenumber'),document.getElementById('number').value);document.getElementById('number').value='';" title="<?=T_("Add")?>">
              <div class="help"><?=T_("Digit the numbers to listen (i.e. <strong>123456</strong>)<br/>or a range of numbers as (<strong>123456-123459</strong>)")?></div>
              <div style="margin: 0.5em 0"><strong><?=T_("DID")?>:</strong> <?=showDid($did);?></div>
            </td>
            <td>
              <select name="phonenumber[]" size="4" onchange="saved = false" ondblclick="editOptions(this)" multiple style="float: left" id="phonenumber">
                <?=$numbers?>
              </select>
              <input type="button" value="<?=T_("Edit")?>" onclick="editOptions(getElementById('phonenumber'))" title="<?=T_("Edit")?>">
              <input type="button" value="<?=T_("X")?>" onclick="deleteOptions(getElementById('phonenumber'))" title="<?=T_("Delete")?>">
              <span id="phonenumberErr"></span>
            </td>
          </tr>
        </table>
      </div>
      <!-- Caller Id -->
      <h2><?=T_("Caller Id")?></h2>
      <p class="blockintro"><?=T_("Set the caller id for this group (it will be shown like: CID Name &lt;CID NUMBER&gt;)")?></p>
      <div class="block">
        <div>
          <dl>
            <dt class="required"><label for="cid[clir]"><?=T_("CLIR")?>:</label></dt>
            <dd><input type="checkbox" id="cid[clir]" name="cid[clir]" value="1" <?if ($cid["clir"]==1) echo "checked=\"checked\""; ?> /> <?=T_("hide caller id dialing with this line")?></dd>
            <dt class="required"><label for="cid[passthrough]"><?=T_("Pass Through")?>:</label></dt>
            <?if(isset($_GET["id"])) {?><dd><input type="checkbox" id="cid[passthrough]" name="cid[passthrough]" value="1" onclick="if(this.checked){xajax_hideCid();}else{xajax_showCid(document.getElementById('off[id]').value);}" <?if ($passthrough==1) echo "checked=\"checked\""; ?> /> <?=T_("use user's caller id on this line")?></dd>
            <?}else{?><dd><input type="checkbox" id="cid[passthrough]" name="cid[passthrough]" value="1" onclick="if(this.checked){xajax_hideCid();}else{xajax_showCid('');}" <?if ($passthrough==1) echo "checked=\"checked\""; ?> /> <?=T_("use user's caller id on this line")?></dd><? } ?>
          </dl>
        </div>
        <div id="callerid">
          <?if($passthrough==0) {?>
          <dl>
            <dt class="required"><label for="cid[cid_name]"><?=T_("CID Name")?>:</label></dt>
            <dd><input type="text" size="25" maxlength="20" id="cid[cid_name]" name="cid[cid_name]" value="<?=$cid['cid_name']?>" /> <?=T_("default caller id name")?></dd>
            <dt class="required"><label for="cid[cid_number]"><?=T_("CID Number")?>:</label></dt>
            <dd><input type="text" size="25" maxlength="100" id="cid[cid_number]" name="cid[cid_number]" value="<?=$cid['cid_number']?>" /> <?=T_("default caller id number")?></dd>
            <dt class="required"><label for="cid[cid_appexten]"><?=T_("Append Exten")?>:</label></dt>
            <dd><input type="checkbox" id="cid[cid_appexten]" name="cid[cid_appexten]" value="1" <?if ($cid["cid_appexten"]==1) echo "checked=\"checked\""; ?> /> <?=T_("append user's extension to CID Number value")?></dd>
            <dt class="required"><label for="cid[force_cid]"><?=T_("Force Default")?>:</label></dt>
            <dd><input type="checkbox" id="cid[force_cid]" name="cid[force_cid]" value="1" <?if ($cid["force_cid"]==1) echo "checked=\"checked\""; ?> /> <?=T_("overwrite user's caller id setting with default line values")?></dd>
          </dl>
          <? } ?>
        </div>
      </div>
      <!-- Tech Options -->
      <? echo listOption($js, IAX2, $optionsArr,false,false,RULE_INCOMING);?>
      <!-- Groups of Office -->
      <? echo listGroup(GROUP_OF_OFFICE, $js, $groups);?>
      <!-- Input Buttons -->
      <div class="action">
        <input type="hidden" id="off[id]" name="off[id]" value="<?=$id?>" />
        <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/></a>
        <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick=" selectAll(getElementById('off[alias]')); selectAll(getElementById('phonenumber')); document.getElementById('alert').innerHTML=''; xajax_processFormData(xajax.getFormValues('mainform')); "/></a>
        <!-- <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/>
        <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" /> -->
      </div>
    </form>
  </div>

  <script>
  function setInKeyRoll(){
    var rollObj = document.getElementById('inKeyRoll');
    if(rollObj != null){
      var html = '<img src=\"<?=$relBasePath?>public/img/ico-progress.gif\" alt=\"loading\" /><span><?=T_("loading")?></span>';
      rollObj.innerHTML = html;
    }
  }
  </script>


  <?
  $contents=ob_get_contents();
  ob_end_clean();

  //================ SIDEBAR ================
  ob_start();
  ?>
    <div class="Sidebar">
      <?$sel="offices";include("../../sidebar.php");?>
      <h1><?=T_("Info")?></h1>
      <p><?=T_("An office is made by:</p><ol><li>general information</li><li>account info</li><li>phone numbers</li></ol><h2>How to add a new phone number</h2><p>Write the office phone number in the textbox and then press <b>+</b>.<br />            Select a number and then press <b>X</b> to delete it. <br /> To edit a number, double click it or select it and then press <b>edit</b>.<br />")?></p>
    </div>
  <?
  $sidebar=ob_get_contents();
  ob_end_clean();

  //================ SETTINGS ================
 	sajax_handle_client_request();
  $smarty->assign("section", "offices");
  $smarty->assign("subsection", "");
  $smarty->assign("templateType", "TwoColLeft");  //OneCol, TwoColLeft, TwoColRight
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->assign("ajax", $js);
  $smarty->display('settings.tpl');
?>
